/***************************************************
 ** @Desc : This file for 用户登录操作
 ** @Time : 2018.12.28 15:59 
 ** @Author : Joker
 ** @File : login_act
 ** @Last Modified by : Joker
 ** @Last Modified time: 2018.12.28 15:59
 ** @Software: GoLand
****************************************************/
package controllers

import (
	"github.com/astaxie/beego"
	"github.com/dchest/captcha"
	"strings"
	"sub_account/models"
	"sub_account/utils"
	"time"
)

type LoginAction struct {
	beego.Controller
}

var user = models.Users{}

//登录
// @router / [get]
func (this *LoginAction) ShowLogin() {
	isLogin := this.GetSession("userName")
	if isLogin != nil {
		this.TplName = "index.html"
	} else {
		capt := struct {
			CaptchaId string
		}{
			captcha.New(),
		}
		this.Data["CaptchaId"] = capt.CaptchaId
		this.TplName = "login.html"
	}
}

//登录行为
// @router /login.py/?:params [post]
func (this *LoginAction) IsLogin() {
	//获取数据
	userNo := strings.TrimSpace(this.GetString("loginNo"))
	pwd := strings.TrimSpace(this.GetString("password"))

	//判断数据
	if userNo != "" && pwd != "" {
		msg := ""
		//没有找到这个用户
		if !user.UserIsExit(userNo) {
			msg = "用户不存在，请联系管理员!"
		}

		//验证密码
		u := user.SelectOneUser(userNo)
		pwdMd5 := global.LoginPasswordSolt(pwd, u.Salt)
		if msg == "" && strings.Compare(pwdMd5, u.LoginPwd) != 0 {
			msg = "密码输入错误!"
		}

		//页面跳转
		out := make(map[string]string)
		if msg == "" {
			//设置cookie，时间为30分钟
			this.Ctx.SetCookie("auth", global.RandomString(32), utils.COOKIE_EXPIRE*time.Second)
			this.SetSession("userName", u.UserName)
			utils.LogInfo("  用户登录成功! ")

			//数据回显
			out["url"] = "/"
		} else {
			out["code"] = "-9"
			out["msg"] = msg
		}
		this.Data["json"] = out
		this.ServeJSON()
	}
	this.TplName = "login.html"
}

/*验证输入的验证码*/
// @router /verifyCaptcha.py/:value/:chaId [get]
func (this *LoginAction) VerifyCaptcha() {
	captchaId := this.Ctx.Input.Param(":chaId")
	captchaValue := this.Ctx.Input.Param(":value")

	verify := captcha.VerifyString(captchaId, captchaValue)
	if verify {
		this.Data["json"] = global.JsonFormat(9, "", "", "")
	} else {
		this.Data["json"] = global.JsonFormat(-9, "", "验证码不匹配!", "")
	}
	this.ServeJSON()
	this.StopRun()
}

/*重绘验证码*/
// @router /flushCaptcha.py/ [get]
func (this *LoginAction) FlushCaptcha() {
	capt := struct {
		CaptchaId string
	}{
		captcha.New(),
	}
	this.Data["json"] = global.JsonFormat(9, capt.CaptchaId, "验证码不匹配!", "")
	this.ServeJSON()
	this.StopRun()
}

/*退出登录*/
//@router /loginOut.py
func (this *LoginAction) LoginOut() {
	this.Ctx.SetCookie("auth", "")
	this.DelSession("userNo")
	this.DelSession("userName")
	this.Redirect(beego.URLFor("LoginAction.ShowLogin"), 302)
}
